<script setup name="login">
import { useStore } from 'vuex';
import { CODE_WAIT_TIME } from '@/constants';
import { throttle } from 'lodash-es';
import * as useApi from '@/api/user';
import * as strategy from '@/constants/strategy';

console.log('before create');

// 按需加载
// lodash-es
// echarts < 5
// vue-element-admin

onActivated(() => {
  console.log(123);
});

onDeactivated(() => {
  console.log(456);
});

const store = useStore();

const mode = ref('account'); // 'account' | 'message'
const countDown = ref(CODE_WAIT_TIME);

const form = ref(null);

const account = localStorage.getItem('account') || '';
const password = localStorage.getItem('password') || '';
const mobile = localStorage.getItem('mobile') || '';
const isMemo = localStorage.getItem('isMemo') === 'true' || true;

const params = reactive({
  account: isMemo ? account : '',
  password: isMemo ? password : '',
  mobile: isMemo ? mobile : '',
  code: '',
  isMemo,
  isAgree: false,
});

function accountChecker(_, value, cb) {
  if (!strategy.ACCOUNT.test(value.trim())) {
    cb(new Error('账号格式错误 应为字母开头 共6-20个字符'));
  } else {
    cb();
  }
}

function mobileChecker(_, value, cb) {
  if (!strategy.MOBILE.test(value.trim())) {
    cb(new Error('手机号格式错误'));
  } else {
    cb();
  }
}

function codeChecker(_, value, cb) {
  if (!strategy.CODE.test(value.trim())) {
    cb(new Error('验证码格式错误'));
  } else {
    cb();
  }
}

function agreeChecker(_, value, cb) {
  if (!value) {
    cb(new Error('不同意不行'));
  } else {
    cb();
  }
}

const rules = reactive({
  account: [{ validator: accountChecker, trigger: 'blur' }],
  mobile: [{ validator: mobileChecker, trigger: 'blur' }],
  code: [{ validator: codeChecker, trigger: 'blur' }],
  isAgree: [{ validator: agreeChecker, trigger: 'change' }],
});

function onLoginWithAccount() {
  form.value.validate(async (valid) => {
    if (valid) {
      const res = await store.dispatch('user/login', params);
      setTimeout(() => {
        res.ctrlr.abort();
      }, 10);
      if (res.success) {
        // 如果勾选了记住我 就记录相关数据
        if (params.isMemo) {
          localStorage.setItem('account', params.account);
          localStorage.setItem('password', params.password);
          localStorage.setItem('isMemo', params.isMemo);
        }
      } else {
        // 失败了清空密码
        params.password = '';
      }
    } else {
      return false;
    }
  });
}

// 验证码登录
async function onLoginWithCode() {
  console.log(1);
}


// 发送验证码
const sendCodeWithCheckSuccess = throttle(() => {
  let timer = null;
  useApi.loginWithCode(params.mobile)
    .then((msg) => {
      ElMessage({
        message: msg,
        type: 'success',
      });
    })
    .catch((msg) => {
      sendCodeWithCheckSuccess.cancel();
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
      ElMessage({
        message: msg,
        type: 'error',
      });
    });
  countDown.value = CODE_WAIT_TIME - 1;
  timer = setInterval(() => {
    countDown.value--;
    if (countDown.value < 1) {
      clearInterval(timer);
      countDown.value = CODE_WAIT_TIME;
    }
  }, 1000);
}, 500);

function sendCode() {
  if (!strategy.MOBILE.test(params.mobile)) {
    return;
  }
  // 成功
  sendCodeWithCheckSuccess();
}

function useMessage() {
  mode.value = 'message';
}
function useAccount() {
  mode.value = 'account';
}
</script>

<template>
  <div class="container">
    <div class="form-wrapper">
      <el-form
        ref="form"
        :rules="rules"
        :model="params"
      >
        <template v-if="mode === 'account'">
          <el-button @click="useMessage">
            使用短信登录
          </el-button>
          <el-form-item prop="account">
            <el-input
              v-model="params.account"
            >
              <template #prepend>
                <i-ep-user class="icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="params.password"
              type="password"
            >
              <template #prepend>
                <i-ep-lock class="icon" />
              </template>
            </el-input>
          </el-form-item>
        </template>
        <template v-else>
          <el-button @click="useAccount">
            使用账号登录
          </el-button>
          <el-form-item prop="mobile">
            <el-input
              v-model="params.mobile"
            >
              <template #prepend>
                <i-ep-user class="icon" :size="24" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="params.code"
            >
              <template #prepend>
                <icon name="dun-pai" :size="24 * .9" color="#fff" />
              </template>
              <template #append>
                <el-button
                  @click="sendCode"
                  :disabled="countDown !== CODE_WAIT_TIME"
                >
                  {{ countDown === CODE_WAIT_TIME ? '发送验证码' : countDown }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </template>
        <el-form-item>
          <el-checkbox
            v-model="params.isMemo"
            label="记住我"
          />
        </el-form-item>
        <el-form-item prop="isAgree">
          <el-checkbox v-model="params.isAgree">
            我已同意
            <a href="">《隐私条款》</a>
            和
            <a href="">《服务条款》</a>
          </el-checkbox>
        </el-form-item>
        <el-button
          type="primary"
          :disabled="!params.isAgree"
          @click="() => mode === 'account' ? onLoginWithAccount() : onLoginWithCode()"
        >
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

  .form-wrapper {
    width: 380px;
    outline: 1px solid red;

    :deep(.el-input-group__prepend) {
      background-color: #cfcdcd;
      padding: 8px;
    }

    .icon {
      font-size: 18px;
      color: white;
    }
  }
}
</style>
